package org.apache.servicecomb.samples.practise.houserush.sale.dao;

import org.apache.servicecomb.samples.practise.houserush.sale.entity.HouseOrder;
import org.apache.servicecomb.samples.practise.houserush.sale.entity.Sale;
import org.apache.servicecomb.samples.practise.houserush.sale.entity.SaleQualification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.persistence.LockModeType;
import java.util.Date;
import java.util.List;

public interface HouseOrderDao extends JpaRepository<HouseOrder, Integer> {

    //统计活动中的房源数量
    int countBySaleId(int saleId);

    HouseOrder findOne(int houseOrderId);
    HouseOrder findAllByHouseId(Integer houseId);
    List<HouseOrder> findAllByCustomerId(int customerId);

    //认购房源
    //条件 房源订单id 和 客户id为空
    //修改的值： 设置客户的id  设置订单状态 设置order时间
    @Modifying
    @Query(value = "UPDATE house_orders SET customer_id =?1,state=?2,ordered_at=?3 " +
            "where id = ?4 and customer_id is null", nativeQuery = true)
    int updateByIdAndCustomerIdIsNull(int customerId, String state, Date orderedAt,int houseOrderId);

    //悲观锁定。其他事务不能同时读取或写入实体。
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT ho FROM HouseOrder ho WHERE ho.id = ?1")
    HouseOrder findOneForUpdate(int id);
}
